﻿using System.Net.Sockets;
using System.Text;

TcpClient client = new TcpClient();

Console.Write("请输入你的用户名：");
string username = Console.ReadLine() ?? "匿名";

client.Connect("127.0.0.1", 5000);
NetworkStream stream = client.GetStream();

_ = Task.Run(() => ReceiveMessages());

Console.WriteLine("已连接服务器，可以开始聊天了...");

while (true)
{
    string? message = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(message)) continue;

    string fullMessage = $"{username}: {message}";
    byte[] buffer = Encoding.UTF8.GetBytes(fullMessage);
    stream.Write(buffer, 0, buffer.Length);
}

void ReceiveMessages()
{
    byte[] buffer = new byte[1024];
    int bytesRead;

    try
    {
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(msg);
        }
    }
    catch
    {
        Console.WriteLine("服务器连接断开。");
    }
}